<template>
	<view class="template-product tn-safe-area-inset-bottom">
		<!-- 顶部自定义导航 -->
		<tn-nav-bar fixed customBack backgroundColor="#FFFFFF">
			<view slot="back" class='tn-custom-nav-bar__back'>
				<text class='icon tn-icon-left' @click="goBack"></text>
				<text class='icon tn-icon-home-capsule-fill' @click="goHome"></text>
			</view>
			订单详情
		</tn-nav-bar>
		<view :style="{paddingTop: vuex_custom_bar_height + 'px'}"></view>

		<view class="tn-margin">
			<view class="tn-flex tn-flex-row-between">
				<view class="justify-content-item tn-text-bold tn-text-xxl">
					{{ detailInfo.title || '暂无标题' }}
				</view>
			</view>
			<view class="tn-flex tn-flex-row-start tn-flex-col-between tn-flex-wrap">
				<view v-for="(label_item,label_index) in detailInfo.techList" :key="label_index"
					class="justify-content-item tn-margin-top-sm tn-margin-right-sm tn-text tn-color-gray--dark">
					<text class="tn-tag-content__item--prefix">#</text>
					{{ getTech(label_item) }}
				</view>
			</view>
			<view class="tn-flex tn-flex-row-between tn-margin-top">
				<view
					:class="[`justify-content-item tn-text-bold tn-color-${orderStatus[detailInfo.orderPayStatus].color}`] ">
					<text class="" style="font-size: 35rpx;">
						{{orderStatus[detailInfo.orderPayStatus].text + (orderStatus[detailInfo.orderPayStatus].remark || '')}}
					</text>
					<block v-if="detailInfo.orderPayStatus == orderStatus[1].value">
						<text class="tn-margin-right-sm" style="font-size: 35rpx;">:</text>
						<text class="tn-text-sm">￥</text>
						<text class="" style="font-size: 50rpx;"> {{ detailInfo.advancePrice || 0}}</text>
					</block>
					<block v-else-if="detailInfo.orderPayStatus == orderStatus[4].value">
						<text class="tn-margin-right-sm" style="font-size: 35rpx;">:</text>
						<text class="tn-text-sm">￥</text>
						<text class="" style="font-size: 50rpx;"> {{ detailInfo.realFinalPaymentPrice || 0}}</text>
					</block>

				</view>
			</view>
			
			<!-- 期望交付日期 -->
			<view class="tn-flex tn-flex-row-between tn-margin-top-sm">
				<view class="justify-content-item" style="font-size: 26rpx; color: #000;">
					期望交付日期：{{ formatDate(detailInfo.expectedDeliveryTime) || '暂无' }}
				</view>
			</view>
		</view>

		<!-- 边距间隔 -->
		<view class="tn-strip-bottom"></view>

		<view class="tn-margin">
			<view class="tn-flex tn-flex-row-between">
				<view class="justify-content-item tn-text-bold tn-text-xl">
					类目&服务
				</view>
			</view>
		</view>

		<view class="">
			<view class="tn-tag-content tn-margin tn-text-justify">
				<!-- 显示类目&服务 -->
				<view v-for="(value, key) in detailInfo.categorySelectionMap" :key="key"
					class="tn-tag-content__item tn-margin-right tn-round tn-text-sm tn-text-bold"
					:class="[`tn-bg-${getColor(parseInt(key))}--light tn-color-${getColor(parseInt(key))}`]">
					<text class="tn-tag-content__item--prefix">#</text> {{ value }}
				</view>
			</view>
		</view>

		<!-- 边距间隔 -->
		<view class="tn-strip-bottom"></view>

		<view class="tn-margin">
			<view class="tn-flex tn-flex-row-between tn-flex-col-center">
				<view class="justify-content-item tn-text-bold tn-text-xl">
					参团成员
				</view>
				<view class="justify-content-item tn-text">
					<block
						v-if="(detailInfo.groupStatus==groupStatus.groupingGoing || detailInfo.myGroupOrderVO != null) && getGroupDaysRemaining() > 0">
						拼团倒计时：
						<tn-count-down separator="ch" ref="countDown" :timestamp="getGroupDaysRemaining()"
							fontSize="28" separatorSize="28" :autoplay="true" @end="endWatch"></tn-count-down>
					</block>
					<block v-else>
						<text :class="[`tn-color-${groupInfo.color}`]">{{groupInfo.text}}</text>
					</block>
				</view>
			</view>
		</view>
		<view class="tn-margin">
			<view class="tn-flex tn-flex-row-start">
				<view v-for="(member, index) in displayGroupMembers" :key="index" class="tn-margin-right-sm">
					<button v-if="member.isPlaceholder" class="tn-avatar-placeholder share-button" open-type="share" @click="handlePlaceholderClick">
						<text class="tn-icon-add tn-color-gray"></text>
					</button>
					<tn-avatar v-else :src="member.src" size="80rpx"></tn-avatar>
				</view>
			</view>
			<!-- 添加提示文字 -->
			<view v-if="displayGroupMembers.some(member => member.isPlaceholder)" class="tn-margin-top-sm">
				<text class="tn-color-gray tn-text-sm">时间截止前至少邀请2人才可成团，最多可邀请10人</text>
			</view>
		</view>

		<!-- 边距间隔 -->
		<view class="tn-strip-bottom"></view>

		<!-- 接单商 -->
		<view class="tn-margin">
			<view class="tn-flex tn-flex-row-between tn-flex-col-center">
				<view class="justify-content-item tn-text-bold tn-text-xl">接单商</view>
				<navigator v-if="displayMerchant" :url="toMerchantInfoUrl(displayMerchant)" class="justify-content-item tn-text">
					详情 <text class="tn-icon-right"></text>
				</navigator>
			</view>
		</view>
		<view class="tn-margin">
			<view v-if="merchantLoading" class="tn-color-gray">加载中...</view>
			<navigator v-else-if="displayMerchant" class="merchant-card" :url="toMerchantInfoUrl(displayMerchant)">
				<!-- 头像 + 姓名（居中） -->
				<view class="merchant-header tn-flex tn-flex-row-center tn-flex-col-center">
					<tn-avatar :src="displayMerchant.headSculpture || '/static/mine/avatar.svg'" size="lg"></tn-avatar>
					<view class="merchant-name tn-text-bold">{{ displayMerchant.nickname || displayMerchant.name || displayMerchant.nickName || displayMerchant.merchantName || '接单商' }}</view>
				</view>
				<!-- 分割线 -->
				<view class="merchant-divider"></view>
				<!-- 指标行 -->
				<view class="merchant-stats tn-flex tn-flex-row-around">
					<view class="stat tn-flex tn-flex-direction-column tn-flex-col-center">
						<view class="value tn-text-bold">{{ displayMerchant.receivingOrdersCount || 0 }}</view>
						<view class="label tn-color-gray tn-text-sm">接单数</view>
					</view>
					<view class="stat tn-flex tn-flex-direction-column tn-flex-col-center">
						<view class="value tn-text-bold">{{ displayMerchant.creditScore != null ? displayMerchant.creditScore : 100 }}</view>
						<view class="label tn-color-gray tn-text-sm">信誉分</view>
					</view>
					<view class="stat tn-flex tn-flex-direction-column tn-flex-col-center">
						<view class="value tn-text-bold">{{ displayMerchant.receivingOrdersDuration ? (displayMerchant.receivingOrdersDuration + '年') : '--' }}</view>
						<view class="label tn-color-gray tn-text-sm">接单经验</view>
					</view>
				</view>
			</navigator>
			<tn-empty v-else mode="list" text="暂无接单商"></tn-empty>
		</view>

		<view class="tn-strip-bottom"></view>
		<view class="tn-margin">
			<view class="tn-flex tn-flex-row-between">
				<view class="justify-content-item tn-text-bold tn-text-xl">
					详情描述
				</view>
			</view>
		</view>

		<view class="tn-margin">
			<rich-text :nodes="detailInfo.requirementDescription || '无'"></rich-text>
		</view>
		<!-- 团购弹窗 -->
		<tn-modal v-model="groupShow" :title="title" :content="groupTip" :button="groupButton"
			@click="modalClick"></tn-modal>
		<!-- 退款弹窗 -->
		<tn-modal v-model="refundShow" :title="title" :content="refundTip" :button="refundButton"
			@click="refundClick"></tn-modal>
		<!-- 下单提醒弹窗 -->
		<tn-modal v-model="buyTipShow" :title="title" :content="buyTip" :button="buyTipButton"
			@click="buyTipShow = false"></tn-modal>

		<!-- 下单按钮-->
		<view class="footerfixed dd-glass tn-padding-left-sm tn-padding-right tn-padding-top-xs tn-padding-bottom-sm"
			v-if="detailInfo.notSale != 1">
			<tn-goods-nav :options="countOptions" :buttonGroups="customButtonGroups" buttonType="round"
				:safeAreaInsetBottom="true" @optionClick="onOptionClick" @buttonClick="onButtonClick"></tn-goods-nav>
		</view>

		<view class='tn-tabbar-height'></view>

		<lm-loading v-if="loading"></lm-loading>

	</view>
</template>

<script>
	import template_page_mixin from '@/libs/mixin/template_page_mixin.js'
	import mpShare from '@/tuniao-ui/libs/mixin/mpShare.js';
	import {
		queryPaperDetail
	} from "@/api";
	import {
		getPayURL,
		queryRefund
	} from "@/api/pay";
	import { getMerchantByOpenId } from "@/api/user";
	import {
		acceptanceGroup
	} from '@/api/groupBuy'
	export default {
		name: 'TemplateProduct',
		mixins: [template_page_mixin, mpShare],
		data() {
			return {
				groupShow: false, //团购弹窗显示
				refundShow: false, //退款弹窗显示
				buyTipShow: false, //下单提醒弹窗显示
				loading: false, //加载显示
				detailInfo: {},
				techDict: {},
				serversDict: {},
				userInfo: {},
				title: '重要提示',
				orderStatus: global.staticDict.orderStatus,
				groupStatus: global.staticDict.groupStatus,
				groupButton: [{
					text: '取消',
					backgroundColor: 'tn-main-gradient-cyan',
					fontColor: '#FFFFFF',
				}, {
					text: '确认发起',
					backgroundColor: 'tn-main-gradient-blue',
					fontColor: '#FFFFFF',
				}],
				refundButton: [{
					text: '取消',
					backgroundColor: 'tn-main-gradient-cyan',
					fontColor: '#FFFFFF',
				}, {
					text: '确认退款',
					backgroundColor: 'tn-main-gradient-blue',
					fontColor: '#FFFFFF',
				}],
				buyTipButton: [{
					text: '关闭',
					backgroundColor: 'tn-main-gradient-blue',
					fontColor: '#FFFFFF',
				}],
				groupInfo: {
					text: "",
					color: "",
				},
				refundTip: "申请退款后，定金原路返回，请确认是否退款！",
				groupTip: "发起团购后无法撤销，且无法参与他人的团购组，发起后请在规定时间内邀请朋友参与，是否发起？",
				buyTip: "请先付定金后，发起团购！",
				countOptions: [{
					icon: 'service-simple-fill',
					openType: "contact",
					text: '在线客服',
				}],
				customButtonGroups: [{
					text: '发起团购',
					backgroundColor: 'tn-cool-bg-color-5',
					color: '#FFFFFF',
					disable: true,
				}, {
					text: '立即付款',
					backgroundColor: 'tn-cool-bg-color-15--reverse',
					color: '#FFFFFF',
					disable: true
				}],
				tagColorList: ['blue', 'green', 'orange', 'purplered', 'purple', 'brown'],
				// 接单商信息
				merchantInfo: null, // 通过 openId 拉取到的商户信息（如果有）
				merchantLoading: false,
			}
		},
		computed: {
			// 统一用于展示的商户数据，优先使用接口返回的 `doUser`，回落到 `merchantInfo`
			displayMerchant(){
				const orderDoUser = (this.detailInfo && (this.detailInfo.doUser || this.detailInfo.merchant || this.detailInfo.user)) || null
				return orderDoUser || this.merchantInfo
			},
			// 显示参团成员（最多11个，包括自己，不足时显示一个加号占位符）
			displayGroupMembers() {
				const members = this.detailInfo.headSculptureDTOS || [];
				const result = [];
				
				// 添加实际成员（最多10个，包括自己）
				const actualMembers = members.slice(0, 10);
				for (let i = 0; i < actualMembers.length; i++) {
					result.push({
						...actualMembers[i],
						isPlaceholder: false
					});
				}
				
				// 如果人数不足10人，添加一个加号占位符
				if (actualMembers.length < 10) {
					result.push({
						src: '',
						isPlaceholder: true
					});
				}
				
				return result;
			}
		},
		async onLoad(query) {
		    //获取字典
			this.getDictInfo = this.$store.getters.getDictInfo
			this.techDict = this.getDictInfo.techDict
			this.serversDict = this.getDictInfo.serversDict
			//获取用户信息
			this.userInfo = this.$store.getters.getUserInfo
			// 接收并保存从订单列表跳转传入的 orderId（若有）
			this.detailInfo.orderId = query.orderId || this.detailInfo.orderId
			this.refresh(query.id);
		},
		methods: {
			// 获取团购倒计时，使用 myGroupOrderVO.groupDaysRemaining
			getGroupDaysRemaining() {
				if (this.detailInfo.myGroupOrderVO && this.detailInfo.myGroupOrderVO.groupDaysRemaining) {
					return parseInt(this.detailInfo.myGroupOrderVO.groupDaysRemaining);
				}
				return 0;
			},
			// 生成商家资料页的跳转链接
			toMerchantInfoUrl(merchant){
				const payload = {
					id: merchant.id || merchant.userId || '',
					nickname: merchant.nickname || merchant.name || merchant.nickName || '',
					receivingOrdersCount: merchant.receivingOrdersCount || 0,
					receivingOrdersDuration: merchant.receivingOrdersDuration || '',
					headSculpture: merchant.headSculpture || '/static/images/mine/avatar.svg',
					creditScore: merchant.creditScore != null ? merchant.creditScore : 100
				}
				const query = encodeURIComponent(JSON.stringify(payload))
				return `/minepages/businessInformation?merchant=${query}`
			},
			// 跳转
			tn(e) {
				uni.navigateTo({
					url: e,
				});
			},
			//底部按钮
			async onButtonClick(param) {
				if (param.index == 0) {
					//非转发分享按钮，显示弹窗
					if (this.customButtonGroups[0].openType != 'share') {
						// 缺少接单商ID时，不允许发起团购
						const hasMerchant = !!(this.detailInfo.merchantOpenid || this.detailInfo.merchantOpenId || this.detailInfo.merchantopenId)
						if (!hasMerchant) {
							uni.$toast({
								message: '暂无接单商，暂不可发起团购',
								duration: 2000,
								type: 'error'
							})
							return
						}
						//只有状态1（待付定金）时才显示付款提示
						if (this.detailInfo.orderPayStatus == this.orderStatus[1].value) {
							this.buyTipShow = true
						} else if (this.detailInfo.orderPayStatus == this.orderStatus[2].value ||
							this.detailInfo.orderPayStatus == this.orderStatus[3].value) {
							//状态2和3直接显示团购弹窗
							this.groupShow = true
						}
					}
				} else if (param.index == 1) {
					// 缺少接单商ID时，不允许付款
					const hasMerchant = !!(this.detailInfo.merchantOpenid || this.detailInfo.merchantOpenId || this.detailInfo.merchantopenId)
					if (!hasMerchant) {
						uni.$toast({
							message: '暂无接单商，暂不可付款',
							duration: 2000,
							type: 'error'
						})
						return
					}
					await this.pay();
				}
			},
			onOptionClick(param) {
				if (param.index == 1) {
					this.refundShow = true;
				}
			},
			//获取颜色
			getColor(index) {
				let color;
				while (index >= 6) {
					index -= 6;
				}
				return this.tagColorList[index]
			},
			//团购弹窗按钮
			async modalClick(param) {
				if (param.index == 1) {
					this.groupShow = false //关闭团购弹窗
					//团购后发起请求
					try {
						const res = await acceptanceGroup(this.detailInfo.orderId);
						console.log('发起团购API返回:', res);
						if (res.code === 200) {
							console.log('发起团购成功，设置状态');
							
							this.loading = true //页面刷新遮布
							// 先刷新数据
							await this.refresh(this.detailInfo.id)
							
							// 然后确保团购状态正确设置
							console.log('刷新后的数据:', {
								groupStatus: this.detailInfo.groupStatus,
								myGroupOrderVO: this.detailInfo.myGroupOrderVO,
								myGroupOrderVO_groupDaysRemaining: this.detailInfo.myGroupOrderVO ? this.detailInfo.myGroupOrderVO.groupDaysRemaining : null
							});
							
							// 如果API返回的数据没有正确的倒计时，强制设置
							if (!this.getGroupDaysRemaining() || this.getGroupDaysRemaining() <= 0) {
								console.log('强制设置倒计时');
								// 设置到 myGroupOrderVO 中
								if (this.detailInfo.myGroupOrderVO) {
									this.detailInfo.myGroupOrderVO.groupDaysRemaining = 3 * 24 * 60 * 60; // 3天倒计时（秒数）
								}
							}
							
							// 如果没有正确的团购状态，强制设置
							if (this.detailInfo.myGroupOrderVO && this.detailInfo.groupStatus != this.groupStatus.groupingGoing) {
								console.log('强制设置团购状态');
								this.detailInfo.groupStatus = this.groupStatus.groupingGoing;
							}
							
							// 重新更新团购信息显示
							this.getGroupInfo();
							
							setTimeout(() => {
								this.loading = false
							}, 1500)
						} else {
							uni.$toast({
								message: res.msg || '发起团购失败',
								duration: 2000,
								type: 'error'
							})
						}
					} catch (e) {
						console.log('发起团购失败:', e)
						uni.$toast({
							message: '发起团购失败，请重试',
							duration: 2000,
							type: 'error'
						})
					}
				} else {
					this.groupShow = false //关闭弹窗
				}
			},
			//退款弹窗按钮
			async refundClick() {
        this.refundShow = false //关闭弹窗
        try {
          const res = await queryRefund(this.detailInfo.orderId,'LM_MAI')
          if (res.code === 200) {
            this.loading = true;
            await this.refresh(this.detailInfo.id)
            setTimeout(() => {
              this.loading = false
            }, 1500)
          }
        } catch (e) {
          console.log(e)
        }
			},
			//获取订单详情
			async getOrderDetail(id) {
				try {
					const res = await queryPaperDetail(id)

					console.log('获取订单详情API返回:', res);
					
					if (res.code === 200) {
						const temp = res.data
						// 处理技术选型，如果字段不存在或为空，则设为空数组
						if (!temp.technicalSelection || temp.technicalSelection == '') {
							temp.techList = []
						} else {
							temp.techList = temp.technicalSelection.split(',')
						}
						// 处理包含服务，如果字段不存在或为空，则设为空数组
						if (!temp.includingServices || temp.includingServices == '') {
							temp.servicesList = []
						} else {
							temp.servicesList = temp.includingServices.split(',')
						}
						// 确保其他必要字段有默认值
						temp.introduction = temp.introduction || '无'
						// 规范化：未参加团购时确保为 null，便于判断
						temp.myGroupOrderVO = temp.myGroupOrderVO ?? null
						
						// 处理头像数据：如果myGroupOrderVO存在且有headSculptureDTOS，则使用它
						if (temp.myGroupOrderVO && temp.myGroupOrderVO.headSculptureDTOS) {
							temp.headSculptureDTOS = temp.myGroupOrderVO.headSculptureDTOS
						} else {
							temp.headSculptureDTOS = temp.headSculptureDTOS || []
						}
						
						// 处理团购倒计时：仅在字段缺失时设置默认值；倒计时<=0时不再重置
						if (temp.myGroupOrderVO != null) {
							// 仅当后端未提供该字段时，设置默认3天
							if (temp.myGroupOrderVO.groupDaysRemaining == null) {
								console.log('groupDaysRemaining 缺失，设置默认倒计时');
								temp.myGroupOrderVO.groupDaysRemaining = 3 * 24 * 60 * 60; // 3天
							}
							// 不强制修正后端的团购状态，只在缺失且仍有倒计时时推断为进行中
							if ((temp.groupStatus === undefined || temp.groupStatus === null) && Number(temp.myGroupOrderVO.groupDaysRemaining) > 0) {
								temp.groupStatus = this.groupStatus.groupingGoing;
							}
						}
						
						// 调试信息
						console.log('订单详情数据:', {
							groupStatus: temp.groupStatus,
							myGroupOrderVO: temp.myGroupOrderVO,
							myGroupOrderVO_groupDaysRemaining: temp.myGroupOrderVO ? temp.myGroupOrderVO.groupDaysRemaining : null,
							headSculptureDTOS: temp.headSculptureDTOS
						});
						
						this.detailInfo = temp
						// 获取接单商信息
						// await this.loadMerchantInfo()
					}
				} catch (e) {
					console.log('获取订单详情失败:', e)
				}
			},
			// 根据 merchantOpenid 获取接单商信息
			// async loadMerchantInfo() {
			// 	const openId = this.detailInfo.merchantOpenid || this.detailInfo.merchantOpenId || this.detailInfo.merchantopenId
			// 	if (!openId) {
			// 		this.merchantInfo = null
			// 		return
			// 	}
			// 	try {
			// 		this.merchantLoading = true
			// 		const res = await getMerchantByOpenId(openId)
			// 		if (res.code === 200) {
			// 			this.merchantInfo = res.data || null
			// 		} else {
			// 			this.merchantInfo = null
			// 		}
			// 	} catch (e) {
			// 		this.merchantInfo = null
			// 	} finally {
			// 		this.merchantLoading = false
			// 	}
			// },
			//支付
			async pay() {
				try {
					let that = this;
					const res = await getPayURL(this.detailInfo.orderId, 'LM_MAI')
					let sign = JSON.parse(res.msg);
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: sign.timeStamp,
						nonceStr: sign.nonceStr,
						package: sign.package,
						signType: sign.signType,
						paySign: sign.paySign,
						success: async function(res) {
							that.loading = true;
							await that.refresh(that.detailInfo.id)
							setTimeout(() => {
								that.loading = false
							}, 1500)
						},
						fail: function(err) {
							uni.$toast({
								message: '支付失败',
								duration: 2000,
								type: 'error'
							})
						}
					})
				} catch (e) {
					console.log(e)
				}
			},
			async endWatch() {
				this.loading = true;
				await this.refresh(this.detailInfo.id)
				setTimeout(() => {
					this.loading = false
				}, 1500)
			},
			//技术选型字典转换
			getTech(techKey) {
				return this.techDict[techKey];
			},
			getServers(serversKey) {
				return this.serversDict[serversKey];
			},
			//格式化日期
			formatDate(dateString) {
				if (!dateString) return '';
				
				try {
					const date = new Date(dateString);
					if (isNaN(date.getTime())) return dateString; // 如果解析失败，返回原字符串
					
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					
					return `${year}年${month}月${day}日`;
				} catch (e) {
					return dateString; // 如果出错，返回原字符串
				}
			},
			//刷新团购信息
			getGroupInfo() {
				const payStatus = Number(this.detailInfo.orderPayStatus)
				const hasMerchant = !!(this.detailInfo.merchantOpenid || this.detailInfo.merchantOpenId || this.detailInfo.merchantopenId)
				
				// 获取团购状态，优先使用 myGroupOrderVO 中的状态
				const currentGroupStatus = this.detailInfo.myGroupOrderVO 
					? this.detailInfo.myGroupOrderVO.groupStatus 
					: this.detailInfo.groupStatus;
				
				// 先处理强制禁用的状态：0 已退款，5 已支付尾款，6 交易结束
				if ([0, 5, 6].includes(payStatus)) {
					this.groupInfo.color = 'gray--dark';
					this.groupInfo.text = '拼团已结束';
					this.customButtonGroups[0].text = '发起团购';
					this.customButtonGroups[0].openType = '';
					this.customButtonGroups[0].disable = true;
					return;
				}

				// 规则：未参加团购 且 订单状态为1（待付定金）、2（定金已支付）、3（尾款待支付）→ 显示"发起团购"且可点
				if (this.detailInfo.myGroupOrderVO == null && [1, 2, 3].includes(payStatus)) {
					this.groupInfo.color = 'green';
					this.groupInfo.text = '未开始拼团';
					this.customButtonGroups[0].text = '发起团购';
					this.customButtonGroups[0].openType = '';
					this.customButtonGroups[0].disable = !hasMerchant;
					return;
				}
				
				// 优先处理明确的团购状态（成功/失败）
				if (currentGroupStatus == this.groupStatus.groupSuccess || Number(currentGroupStatus) === 3) {
					this.groupInfo.color = 'blue';
					this.groupInfo.text = '拼团成功';
					this.customButtonGroups[0].disable = true;
					return;
				}
				
				if (currentGroupStatus == this.groupStatus.groupFail || Number(currentGroupStatus) === 4) {
					this.groupInfo.color = 'purplered';
					this.groupInfo.text = '拼团未成功';
					this.customButtonGroups[0].disable = true;
					return;
				}
				
				// 处理团购进行中的状态
				if (this.detailInfo.myGroupOrderVO != null) {
					if (this.getGroupDaysRemaining() > 0) {
						// 倒计时未结束，显示进行中
						this.groupInfo.color = 'green';
						this.groupInfo.text = '拼团进行中';
						// 确保倒计时能够启动
						this.$nextTick(() => {
							if (this.$refs.countDown) {
								console.log('准备启动倒计时, 剩余时间:', this.getGroupDaysRemaining());
								try {
									this.$refs.countDown.start();
									console.log('倒计时启动成功');
								} catch (e) {
									console.log('倒计时启动失败:', e);
								}
							} else {
								console.log('倒计时组件未找到');
							}
						})
						this.customButtonGroups[0].text = '邀请好友团购';
						this.customButtonGroups[0].openType = 'share';
						this.customButtonGroups[0].disable = false;
					} else {
						// 倒计时结束，再次检查团购状态
						if (currentGroupStatus == this.groupStatus.groupSuccess || Number(currentGroupStatus) === 3) {
							this.groupInfo.color = 'blue';
							this.groupInfo.text = '拼团成功';
						} else if (currentGroupStatus == this.groupStatus.groupFail || Number(currentGroupStatus) === 4) {
							this.groupInfo.color = 'purplered';
							this.groupInfo.text = '拼团未成功';
						} else {
							// 倒计时结束但状态不明确，默认显示已结束
							this.groupInfo.color = 'gray--dark';
							this.groupInfo.text = '拼团已结束';
						}
						this.customButtonGroups[0].disable = true;
					}
				} else {
					// 没有团购记录，显示已结束
					this.groupInfo.color = 'gray--dark';
					this.groupInfo.text = '拼团已结束';
					this.customButtonGroups[0].disable = true;
				}
			},
			//根据不同的状态底部按钮显示不同
			handleButton(staus) {
				const canPayByStatus = (staus == this.orderStatus[1].value || staus == this.orderStatus[4].value)
				const hasMerchant = !!(this.detailInfo.merchantOpenid || this.detailInfo.merchantOpenId || this.detailInfo.merchantopenId)
				this.customButtonGroups[1].disable = !(canPayByStatus && hasMerchant)
				//订单可退款
				if (staus == this.orderStatus[2].value) {
					let option = {
						icon: "refund",
						text: "申请退款"
					}
					this.countOptions[1] = option
				} else {
					if(this.countOptions.length>1){
						this.countOptions.pop()
					}
				}

			},
			//刷新订单数据
			async refresh(id) {
				await this.getOrderDetail(id)
				this.handleButton(this.detailInfo.orderPayStatus)
				this.getGroupInfo()
				//设置团购分享
				this.setShare();
			},
			//分享内容
			setShare() {
				console.log("被点击");
				
				// 检查必要的参数
				if (!this.detailInfo.myGroupOrderVO || !this.detailInfo.myGroupOrderVO.groupId) {
					console.error('setShare: 缺少团购ID', this.detailInfo.myGroupOrderVO);
					return false;
				}
				
				// 设置默认的转发参数
				this.$tn.mpShare = {
					// 分享的标题，默认为小程序名称
					title: '(*^▽^*)一起团购吧😽！',
					// 分享的路径，默认为当前页面
					path: `/homepages/afterShareOrder?groupId=${this.detailInfo.myGroupOrderVO.groupId}`,
					// 分享时显示的图片，默认为当前页面截图
					imageUrl: 'https://lemawuyou.oss-cn-shanghai.aliyuncs.com/client/images/groupPurchase.png',
					// 当前页面是否可以分享
					share: true
				}
				
				console.log('setShare: 分享参数设置成功', this.$tn.mpShare);
				return true;
			},
			// 处理参团成员占位符点击
			handlePlaceholderClick() {
				// 检查是否已发起团购
				if (this.detailInfo.myGroupOrderVO == null) {
					uni.showToast({
						title: '请先发起团购',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				// 根据团购状态处理
				switch (this.detailInfo.groupStatus) {
					case this.groupStatus.groupingGoing:
						if (this.getGroupDaysRemaining() > 0) {
							// 团购进行中且倒计时未结束，可以邀请
							if (this.setShare()) {
								uni.showToast({
									title: '分享已设置，请点击右上角分享按钮邀请好友',
									icon: 'success',
									duration: 3000
								});
							} else {
								uni.showToast({
									title: '分享设置失败，请重试',
									icon: 'error',
									duration: 2000
								});
							}
						} else {
							// 倒计时已结束
							uni.showToast({
								title: '团购时间已结束',
								icon: 'none',
								duration: 2000
							});
						}
						break;
						
					case this.groupStatus.groupSuccess:
						uni.showToast({
							title: '拼团已成功',
							icon: 'success',
							duration: 2000
						});
						break;
						
					case this.groupStatus.groupFail:
						uni.showToast({
							title: '拼团已失败',
							icon: 'none',
							duration: 2000
						});
						break;
						
					default:
						// 其他状态，尝试设置分享
						if (this.setShare()) {
							uni.showToast({
								title: '分享已设置，请点击右上角分享按钮邀请好友',
								icon: 'success',
								duration: 3000
							});
						} else {
							uni.showToast({
								title: '分享设置失败，请重试',
								icon: 'error',
								duration: 2000
							});
						}
						break;
				}
			},

		}

	}
</script>

<style lang="scss" scoped>
	.template-product {}

	.tn-tabbar-height {
		min-height: 120rpx;
		height: calc(140rpx + env(safe-area-inset-bottom) / 2);
	}

	/* 胶囊*/
	.tn-custom-nav-bar__back {
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		box-sizing: border-box;
		background-color: rgba(0, 0, 0, 0.15);
		border-radius: 1000rpx;
		border: 1rpx solid rgba(255, 255, 255, 0.5);
		color: #FFFFFF;
		font-size: 18px;

		.icon {
			display: block;
			flex: 1;
			margin: auto;
			text-align: center;
		}

		&:before {
			content: " ";
			width: 1rpx;
			height: 110%;
			position: absolute;
			top: 22.5%;
			left: 0;
			right: 0;
			margin: auto;
			transform: scale(0.5);
			transform-origin: 0 0;
			pointer-events: none;
			box-sizing: border-box;
			opacity: 0.7;
			background-color: #FFFFFF;
		}
	}



	/* 间隔线 start*/
	.tn-strip-bottom {
		width: 100%;
		border-bottom: 20rpx solid rgba(241, 241, 241, 0.8);
	}

	/* 标题 start */
	.nav_title {
		-webkit-background-clip: text;
		color: transparent;

		&--wrap {
			position: relative;
			display: flex;
			height: 120rpx;
			font-size: 46rpx;
			align-items: center;
			justify-content: center;
			font-weight: bold;
			background-image: url(https://resource.tuniaokj.com/images/title_bg/title44.png);
			background-size: cover;
		}
	}

	/* 标题 end */

	/* 底部tabbar start*/
	.footerfixed {
		position: fixed;
		width: 100%;
		bottom: 0;
		z-index: 999;
		background-color: #FFFFFF;
		box-shadow: 0rpx 0rpx 30rpx 0rpx rgba(0, 0, 0, 0.07);
	}

	/* 标签内容 start*/
	.tn-tag-content {
		&__item {
			display: inline-block;
			line-height: 45rpx;
			padding: 10rpx 30rpx;
			margin: 20rpx 20rpx 5rpx 0rpx;

			&--prefix {
				padding-right: 10rpx;
			}
		}
	}
	.merchant-card {
		padding: 20rpx;
		// background: #FFFFFF;
		border-radius: 16rpx;
		// box-shadow: 0rpx 0rpx 30rpx 0rpx rgba(0, 0, 0, 0.07);
	}

	.merchant-header {
		padding: 10rpx 0 20rpx;
	}

	.merchant-name {
		margin-left: 20rpx;
		font-size: 32rpx;
	}

	.merchant-divider {
		height: 2rpx;
		margin: 10rpx 0 20rpx;
		background-color: rgba(0, 0, 0, 0.06);
	}

	.merchant-stats {
		text-align: center;
	}

	.merchant-stats .value {
		font-size: 36rpx;
	}
	
	/* 头像占位符样式 */
	.tn-avatar-placeholder {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #f5f5f5;
		border: 2rpx dashed #d0d0d0;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		transition: all 0.3s ease;
		position: relative;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}
	
	/* 分享按钮特定样式 */
	.share-button {
		padding: 0;
		margin: 0;
		line-height: 1;
		font-size: inherit;
		color: inherit;
		background: transparent;
		outline: none;
	}
	
	.share-button::after {
		border: none;
	}
	
	.tn-avatar-placeholder:active {
		background-color: #e8e8e8;
		transform: scale(0.95);
		box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.15);
	}
	
	.tn-avatar-placeholder .tn-icon-add {
		font-size: 32rpx;
		color: #999;
		transition: color 0.3s ease;
	}
	
	.tn-avatar-placeholder:active .tn-icon-add {
		color: #666;
	}
	
	/* 添加悬停效果提示 */
	.tn-avatar-placeholder::after {
		content: '';
		position: absolute;
		top: -4rpx;
		left: -4rpx;
		right: -4rpx;
		bottom: -4rpx;
		border-radius: 50%;
		border: 2rpx dashed transparent;
		transition: all 0.3s ease;
		pointer-events: none;
	}
	
	.tn-avatar-placeholder:active::after {
		border-color: #007aff;
		opacity: 0.6;
	}
</style>